package com.yaoyong.yy_demo.module.rabbitmq.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.yaoyong.yy_demo.module.rabbitmq.util.ConnectionUtil;

public class Consumer1 {

    private final static String QUEUE_NAME = "test_queue_work";

    public static void main(String[] argv) throws Exception {

        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        /**
         * 注意:RabbitMQ不允许您使用不同的参数重新定义现有队列
         * 生产者和消费者设置需要保持一致
         */
        // 声明队列并持久化
        boolean durable = true;
        channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
        //在处理并确认上一条消息之前一次接收一条消息
        int prefetchCount = 1 ;
        channel.basicQos(prefetchCount);
        //传送回调
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            try {
                //模拟执行效率
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(" [x] Received '" + message + "'");
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };
        //手动确认消息
        boolean autoAck = false;
        // 监听队列
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
    }
}